<template>
  <topic-info :info="info" :info-count="infoCount"></topic-info>
  <space-posts ref="listRef" :list="posts" @onLoad="handleLoad"></space-posts>
</template>

<script>
import { reactive, toRefs, watch } from 'vue'
import TopicInfo from './info'
import SpacePosts from '@/views/Space/posts'
import { topicApi } from '@/api'
export default {
    name: 'Topic',
    components: {
      TopicInfo,
      SpacePosts
    },
    props: {
      name: {
        type: String,
        required: true
      }
    },
    setup(props) {
      const params = reactive({
        listRef: null,
        info: null,
        infoCount: null,
        nextPostId: null,
        posts: []        
      })          

      const initData = async () => {
        try {
          await getInfo()
          await Promise.all([
            getActiveUser(),
            getPosts()
          ])
        } catch (error) {
          console.log(error)
        }
      }

      const getInfo = async () => {
        try {
          const { data } = await topicApi.getInfo({
            tag_name: props.name
          })
          if (data) {
            params.info = data          
          }
        } catch (error) {
          throw new Error(error)
        }
      }

      const getActiveUser = async () => {        
        try {
          const { data } = await topicApi.getActiveUsers({
            topic_id: params.info.tag_id
          })
          if (data) {
            params.infoCount = data           
          }
        } catch (error) {
          console.log(error)
        }
      }

      const getPosts = async () => {
        try {
          const { data } = await topicApi.getRelated({
              topic_id: params.info.tag_id,
              topic_name: params.info.tag_name,
              offset: params.nextPostId || ''
          })
          if (data) {                
            const { has_more, cards } = data
            if (has_more === 0) {
              params.nextPostId = -1                
              complete()
            } else {
              params.nextPostId = cards[cards.length - 1].desc.dynamic_id_str
              params.posts.push(...cards)                
            }  
          }
        } catch (error) {
          console.log(error)
        } finally {
          stopLoading()
        }
      }

      const handleLoad = () => {
        if (params.nextPostId === -1) {
          complete()
          return
        }
        getPosts()
      }

      const complete = () => {
        params.listRef?.complete()
      }

      const stopLoading = () => {
        params.listRef?.stopLoading()
      }
      
      watch(() => props.name, () => {
        initData()
      }, {
        immediate: true
      })

      return {
        ...toRefs(params),
        handleLoad
      }
    }
}
</script>

<style>

</style>